package org.adorsys.aderp.orga.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.adorsys.aderp.orga.domain.OrgaRelation;
import org.adorsys.aderp.orga.service.OrgaPersonService;
import org.adorsys.aderp.orga.service.OrgaRelationRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/orgapeople/{personId}/orgarelationstarget")
@Controller
@RooWebScaffold(path = "orgarelationstarget", formBackingObject = OrgaRelation.class)
public class OrgaRelationTargetController {

	@Autowired
	OrgaPersonService orgaPersonService;
	@Autowired
	OrgaRelationRoleService orgaRelationRoleService;
	
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@PathVariable(value="personId")Long personId,
    		@Valid OrgaRelation orgaRelation, BindingResult bindingResult, 
    		Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, orgaRelation, personId);
            return "orgarelationstarget/create";
        }
        uiModel.asMap().clear();
        orgaRelationService.saveOrgaRelation(orgaRelation);
        return "redirect:"+
        "/orgapeople/" + encodeUrlPathSegment(personId.toString(), httpServletRequest)
        +"/orgarelationsarget/" + encodeUrlPathSegment(orgaRelation.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(@PathVariable(value="personId")Long personId,
    		Model uiModel) {
        populateEditForm(uiModel, new OrgaRelation(),personId);
        List<String[]> dependencies = new ArrayList<String[]>();
        if (orgaRelationRoleService.countAllOrgaRelationRoles() == 0) {
            dependencies.add(new String[] { "orgarelationrole", "orgarelationroles" });
        }
        if (orgaPersonService.countAllOrgapeople() == 0) {
            dependencies.add(new String[] { "orgaperson", "orgapeople" });
        }
        if (orgaPersonService.countAllOrgapeople() == 0) {
            dependencies.add(new String[] { "orgaperson", "orgapeople" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "orgarelationstarget/create";
    }
    
    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable(value="personId")Long personId,
    		@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("orgarelation", orgaRelationService.findOrgaRelation(id));
        uiModel.addAttribute("itemId", id);
        return "orgarelationstarget/show";
    }
    
    @RequestMapping(produces = "text/html")
    public String list(@PathVariable(value="personId")Long personId,
    		@RequestParam(value = "page", required = false) Integer page, 
    		@RequestParam(value = "size", required = false) Integer size, 
    		Model uiModel, HttpServletRequest httpServletRequest) {
        return "redirect:"+
        "/orgapeople/" + encodeUrlPathSegment(personId.toString(), httpServletRequest);
    }
    
    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@PathVariable(value="personId")Long personId,
    		@Valid OrgaRelation orgaRelation, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, orgaRelation, personId);
            return "orgarelationstarget/update";
        }
        uiModel.asMap().clear();
        orgaRelationService.updateOrgaRelation(orgaRelation);
        return "redirect:"+
        "/orgapeople/" + encodeUrlPathSegment(personId.toString(), httpServletRequest)
        +"/orgarelationstarget/" + encodeUrlPathSegment(orgaRelation.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable(value="personId")Long personId,
    		@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, orgaRelationService.findOrgaRelation(id), personId);
        return "orgarelationstarget/update";
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable(value="personId")Long personId,
    		@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        OrgaRelation orgaRelation = orgaRelationService.findOrgaRelation(id);
        orgaRelationService.deleteOrgaRelation(orgaRelation);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/orgarelationstarget";
    }
    
    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("orgaRelation_fromdate_date_format", "dd-MM-yyyy hh:mm:ss");
        uiModel.addAttribute("orgaRelation_todate_date_format", "dd-MM-yyyy hh:mm:ss");
    }
    
    void populateEditForm(Model uiModel, OrgaRelation orgaRelation) {
        uiModel.addAttribute("orgaRelation", orgaRelation);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("orgapeople", orgaPersonService.findAllOrgapeople());
        uiModel.addAttribute("orgarelationroles", orgaRelationRoleService.findAllOrgaRelationRoles());
    }
    
    void populateEditForm(Model uiModel, OrgaRelation orgaRelation, Long personId) {
        uiModel.addAttribute("orgaRelation", orgaRelation);
        addDateTimeFormatPatterns(uiModel);
        
        if(orgaRelation.getPerson()!=null){
        	uiModel.addAttribute("orgapeople", 	Collections.singleton(orgaRelation.getPerson()));
        } else {
        	uiModel.addAttribute("orgapeople", orgaPersonService.findOrgaPerson(personId));
        	orgaRelation.setPerson(orgaPersonService.findOrgaPerson(personId));
        }
        
        if(orgaRelation.getTargetPerson()!=null){
        	uiModel.addAttribute("targetpeople", 	Collections.singleton(orgaRelation.getTargetPerson()));
        } else {
            uiModel.addAttribute("targetpeople", orgaPersonService.findAllOrgapeople());
        }
        
        if(orgaRelation.getRelationRole()!=null){
            uiModel.addAttribute("orgarelationroles", Collections.singleton(orgaRelation.getRelationRole()));
        } else {
            uiModel.addAttribute("orgarelationroles", orgaRelationRoleService.findAllOrgaRelationRoles());
        }
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
    
}
